package org.study.springboot.restful.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.study.springboot.restful.model.Article;
import org.study.springboot.restful.model.RespBean;

import java.util.Date;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/10/8 7:12 下午
 */
@Slf4j
@RequestMapping("/rest")
public class ArticleController {

    /**
     * 获取一篇Article，使用GET方法,根据id查询一篇文章
     * @param id
     * @return
     */
    // @RequestMapping(value = "/articles/{id}",method = RequestMethod.GET)
    @GetMapping("/articles/{id}")
    public RespBean getArticle(@PathVariable("id") Long id) {

        //使用lombok提供的builder构建对象
        Article article = Article.builder()
                .id(id)
                .author("zhangsan")
                .content("spring boot 从青铜到王者")
                .createTime(new Date())
                .title("t1")
                .build();

        log.info("article:" + article);

        return RespBean.ok(article);
    }


    /**
     * 增加一篇Article ，使用POST方法(RequestBody方式接收参数)
     * @param article
     * @return
     */
    // @RequestMapping(value = "/articles",method = RequestMethod.POST)
    @PostMapping("/articles")
    public RespBean saveArticle(@RequestBody Article article) {
        log.info("saveArticle:" + article);
        return RespBean.ok(article);
    }

    /**
     * 增加一篇Article ，使用POST方法(RequestParam方式接收参数)
     */
    /*@PostMapping("/articles")
    public RespBean saveArticle(@RequestParam  String author,
                                  @RequestParam  String title,
                                  @RequestParam  String content,
                                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
                                  @RequestParam  Date createTime){

    log.info("saveArticle:" + createTime);
    return RespBean.ok();
    }*/

    /**
     * 更新一篇Article，使用PUT方法，以id为主键进行更新
     */
    //@RequestMapping(value = "/articles",method = RequestMethod.PUT)
    @PutMapping("/articles")
    public RespBean updateArticle(@RequestBody Article article){
        if(article.getId() == null){
            //article.id是必传参数，因为通常根据id去修改数据
            //TODO 抛出一个自定义的异常
        }

        log.info("updateArticle:" + article);
        return RespBean.ok();
    }

    /**
     * 删除一篇Article，使用DELETE方法，参数是id
     * @param id
     * @return
     */
    //@RequestMapping(value = "/articles/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/articles/{id}")
    public RespBean deleteArticle(@PathVariable("id") Long id){

        log.info("deleteArticle:" + id);
        return RespBean.ok();
    }

}
